<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8" isELIgnored="false"%>
<%@ include file="/WEB-INF/views/shared/taglib.jsp"%>
<%
	request.setAttribute("modelConfigPath", "billing");
%>
<%@ include file="/WEB-INF/views/shared/master/contentHeader.jsp"%>
<style >
	#outStockInfoCopy{display:none}
	td input{height:21px; width:98%;border:none;}
	td{height:21px;padding: 2px 2px !important;text-align:center }
	#area{
		height:354px;
		overflow-y:auto; 
		overflow-x:hidden; 
	}
</style>
<ul class="nav nav-tabs nav-tabs-component " style="margin-bottom: 0px;">
	<li class="active"><a href="#category-tab" data-toggle="tab" >订单详情</a></li>
	<li><a href="#billingRecord-tab" data-toggle="tab" >订单操作记录</a></li>
</ul>
<div class="tab-content">
	<div class="tab-pane active" id="category-tab">
		<t:panel cssClass="panel-flat form-detailed" customBody="true" customHead="true">
			<div class="detailed-navbar-content panel-body">
				<input type="hidden" value='${stocksJson}' id="stocksJson" />
				<input type="hidden" value='${typeJson}' id="typeJson" />
				<input type="hidden" value='${billingJson}' id="billingJson" />
				<t:form modelAttribute="billing" action="/billing/returnOfCargo/save" method="post" cssClass="form-horizontal">
					<div class="hide">
						 <t:hidden path="billingId"/>
		 				 <t:hidden path="deleteMark"/>	
		 				 <t:hidden path="createUserName"/>
				 		 <t:hidden path="createUserId"/>
				 		 <t:hidden path="createDate"/>
				 		 <t:hidden path="shopId"/>
				 		 <t:hidden path="confirm"/>
					</div>
		            <t:formgroup>
		            	<t:label path="billingNo" cssClass="col-sm-1 col-xs-1" />
		                <t:input readonly="true" path="billingNo" colClass="col-sm-2 col-xs-2" />
		                <t:label path="customerId" cssClass="col-sm-1 col-xs-1" />
		                <t:select2 path="customerId" placeholder="请填写客户" allowClear="true" colClass="col-sm-2 col-xs-2"></t:select2>
		                
		            	<t:label path="deliveryDate" cssClass="col-sm-1 col-xs-1" />
		                <t:date  path="deliveryDate" colClass="col-sm-2 col-xs-2"></t:date>
		                <t:label path="businessId" cssClass="col-sm-1 col-xs-1" />
		                <t:select2 path="businessId" placeholder="业务员" allowClear="true" colClass="col-sm-2 col-xs-2"></t:select2>
		            </t:formgroup>
		            <t:formgroup>
		            	<t:label path="billingMoney" cssClass="col-sm-1 col-xs-1" />
						<t:input path="billingMoney" colClass="col-sm-2 col-xs-2" />
		                <t:label path="discount" cssClass="col-sm-1 col-xs-1" />
						<t:input path="discount" colClass="col-sm-2 col-xs-2" />
		            	<t:label path="comment" cssClass="col-sm-1 col-xs-1" />
						<t:input path="comment" colClass="col-sm-2 col-xs-2" />
					</t:formgroup>
		            <div id="area">
		            <table  class="cntable table table-bordered dataTable table-billing">
			            <thead>
				            <tr class="success">
				            	<th style="width:80px">序号</th>
				            	<th style="width:80px">操作</th>
				            	<th style="width:150px">商品编码</th>
		            			<th style="width:200px">商品名称</th>
				            	<th style="width:120px">规格</th>
				            	<th style="width:100px">单位</th>
				            	<th style="width:100px">数量</th>
				            	<th style="width:100px">单价</th>
				            	<th>小计</th>
			            	</tr>
			            </thead>
			            
			            <tbody id="outStockInfo">
			            
							<c:set var="sequence"  value="0"/>
							<c:if test="${type eq 'modify' || type eq 'check'}" >
								<c:forEach var="outStockShow" items="${billing.outStock.outStockShows}">
									<c:forEach var="outStockCollocation" items="${outStockShow.outStockCollocations}" >
										
										<tr id="outStockCollocation_${sequence}">
											<td style="display:none"><input id="collocationId_${sequence}" name="collocationId" type="text" value="${outStockCollocation.collocationId}"/></td>
											<td style="display:none"><input id="cargoId_${sequence}" name="cargoId" type="text" value="${outStockShow.cargoId}"/></td>
											<td name="index"></td>
											<td id="logo" >
								            	<div class="col-md-6 col-sm-6" onclick="addData()" ><i class="fa fa-plus-square"></i></div>
								            	<div class="col-md-6 col-sm-6" onclick="deleteData('outStockCollocation_${sequence}')"><i class="fa fa-minus-square"></i></div>
							            	</td>						
							            	<td><input style="ime-mode:disabled" id="cargoNo_${sequence}" name="cargoNo" type="text" value="${outStockShow.cargo.cargoNo}"></input></td>
							            	<td><input style="ime-mode:disabled" disabled="disabled" id="cargoName_${sequence}" name="cargoName" type="text" value="${outStockShow.cargo.cargoName}"/></td>
							            	<td><input style="ime-mode:disabled" disabled="disabled" id="propertyName_${sequence}" name="propertyName" type="text" value="${outStockCollocation.collocation.propertyNameOne}/${outStockCollocation.collocation.propertyNameTwo}"/></td>
							            	<td ><input style="ime-mode:disabled" disabled="disabled" id="unit_${sequence}" name="unit" type="text" value="${outStockShow.cargo.unit}"/></td>
											
											<td><input style="ime-mode:disabled"  onkeyup="return ValidateNumber(this,value)" id="collocationNum_${sequence}"  name="collocationNum" type="text" value="${outStockCollocation.collocationNum}"/></td>
											<td><input style="ime-mode:disabled"  onkeyup="return ValidateNumber(this,value)" id="realPrice_${sequence}" name="realPrice" type="text" value="${outStockCollocation.realPrice}"/></td>
											<td><input style="ime-mode:disabled" id="subtotal_${sequence}" name="subtotal" type="text" value="${outStockCollocation.realPrice*outStockCollocation.collocationNum}"/></td>
										</tr>
										<c:set var="sequence"  value="${sequence +1}"/>
									</c:forEach>
								</c:forEach>
								
							</c:if>
						</tbody>
		            </table>
					</div>
				</t:form>
			</div>
			<c:if test="${type eq 'add' }" >
				<t:panelFoot headingBtnCssClass="heading-btn pull-right-important">
					<t:button icon="icon-floppy-disk" onclick="saveData()" laddaType="progress" cssClass="btn-info" csize="sm">保存</t:button>
				</t:panelFoot>
			</c:if>
		</t:panel>
	</div>
	<div class="tab-pane" id="billingRecord-tab">
		<iframe id="billingRecordIframe" name="billingRecordIframe" scrolling="auto" frameborder="0"
				scrolling="yes" width="100%" height="100%"  data-src="<c:url value='/billing/billingRecord/index?billingId=${billing.billingId }'/>">
        </iframe>
	</div>
</div>
<table id="outStockInfoCopy">
	<tbody id="outStockInfoCopyBody">
		<tr id="outStockCollocation_temp">
			<td style="display:none"><input id="collocationId_temp" name="collocationId" type="text" value="${outStockCollocation.collocationId}"/></td>
			<td style="display:none"><input id="cargoId_temp" name="cargoId" type="text" value="${cargoId}"/></td>
			<td name="index"></td>
			<td id="logo" >
		          	<div class="col-md-6 col-sm-6" onclick="addData()" ><i class="fa fa-plus-square"></i></div>
		          	<div class="col-md-6 col-sm-6" onclick="deleteData('outStockCollocation_temp')"><i class="fa fa-minus-square"></i></div>
		    </td>						
         	<td colspan="2"><select style="ime-mode:disabled" id="cargoNo_temp" name="cargoNo" type="text" value="${outStockCollocation.collocationId}"><option value=""></option></select></td>
         	<td style="display:none;"><input style="ime-mode:disabled;" disabled="disabled" id="cargoNoShow_temp" name="cargoNoShow" type="text" value="${outStockShow.cargo.cargoNo}"/></td>
         	<td style="display:none;"><input style="ime-mode:disabled" disabled="disabled" id="cargoName_temp" name="cargoName" type="text" value="${outStockShow.cargo.cargoName}"/></td>
         	<td><input style="ime-mode:disabled" disabled="disabled" id="propertyName_temp" name="propertyName" type="text" value="${outStockCollocation.collocation.propertyNameOne}/${outStockCollocation.collocation.propertyNameTwo}"/></td>
         	<td ><input style="ime-mode:disabled" disabled="disabled" id="unit_temp" name="unit" type="text" value=""/></td>
	
			<td><input style="ime-mode:disabled"  onkeyup="return ValidateNumber(this,value)" id="collocationNum_temp"  name="collocationNum" type="text" value="${outStockCollocation.collocationNum}"/></td>
			<td><input style="ime-mode:disabled"  onkeyup="return ValidateNumber(this,value)" id="realPrice_temp" name="realPrice" type="text" value="${outStockCollocation.realPrice}"/></td>
			<td><input style="ime-mode:disabled" id="subtotal_temp" name="subtotal" type="text" value=""/></td>
		</tr>
	</tbody>
</table>
<script type="text/javascript">

$(function(){
	outStockInfo = $("#outStockInfoCopyBody").html();
	$('#pic').popover({
	     trigger : 'hover',//鼠标以上时触发弹出提示框
	     html:true,//开启html 为true的话，data-content里就能放html代码了
	     content:"<img src='<c:url value='/images/hu.jpg'/>' >"
	 });
	
	var productNo=$('#productNo').text();
	if(!$.isNull(productNo)){
	 showMark=true;
	 
	}
	
	$("[name='realPrice']").change(function(){
		/* alert($("[name='realPrice']").val()); */
	});
	$('#discount').bind('input propertychange', function() {
		var discount = parseFloat($(this).val());
		if(isNaN(discount)){
			discount = 0;
			$(this).val(0);
		}else if(discount>10){
			discount = 10;
			$(this).val(10);
		}
		updateBillingMoney();
	});
	
	if(!$.isNull($("#typeJson").val())){
		var type =JSON.parse($("#typeJson").val());
		if(type=="modify"||type=="check"){
			loadBilling();
		}
		if(type=="add"){
			stocksShow(0);
		}
	}
	indexChange();
	
	iframeLazyOpen();
	tabpaneResize();

})

function iframeLazyOpen(){
	$(".nav.nav-tabs.nav-tabs-component li a").click(function(){
		var iframeTab = $(this).attr("href");
		var iframeId = iframeTab.substring(0,iframeTab.indexOf("-")) + "Iframe";
		$(iframeId).attr("src",$(iframeId).attr("data-src"));
	});
}

function tabpaneResize(){
	$(".tab-pane").height($(window).height() - 50);	
	$(window).bind("resize",function(){$(".tab-pane").height($(window).height() - 50)});	
}

function loadBilling(){
	num--;
	if(!$.isNull($("#billingJson").val())){
		var billing =JSON.parse($("#billingJson").val());

		billing.outStock.outStockShows.forEach(function(element,index){
			element.outStockCollocations.forEach(function(outStockCollocation,index){
				num++;
				updateSubtotal(num);

			});
		});
	}
		
}

var outStockInfo;
var newOutStockInfo;
var num=0;
function addData(){
	num++;
	
	newOutStockInfo=outStockInfo.replace(/1/g,num+1);
	newOutStockInfo=newOutStockInfo.replace(/temp/g,num);

	$("#outStockInfo").append(newOutStockInfo);
	stocksShow(num);
	indexChange();
}

function deleteData(deleteId){
	if(index!=3){
		$("#"+deleteId).remove();
		updateBillingMoney();
		indexChange();
	}

}
var index;
function indexChange(){
	index=1;
	$("td[name='index']").each(function(){
		$(this).html(index);	
		index++;
	});
}


function saveData(lBtn){
	var isRepetition = false;
	var collocationIds=[];
	$("input[name='collocationId']").each(function(){
		collocationIds.push({
			id:$(this).val(),
			text:$(this).val()
		})
	});

	for(var i=0;i<collocationIds.length;i++){
		console.log(collocationIds[i].id);
		for(var j=i+1;j<collocationIds.length;j++){
			if(collocationIds[i].id!=""||collocationIds[j].id!=""){
				if(collocationIds[i].id==collocationIds[j].id){
					isRepetition=true;
				}
			}
			
		}
	}
	if(isRepetition){
		$.showTips("存在相同货品！",1000,"warning");
		return;
	}
	
	var isSave=false;
	$("input[name='collocationId']").each(function(){
		if($(this).val()!=null && $(this).val() != ""){
			isSave=true;
		}
						
	});
	if(!isSave){
		$.showTips("请选择开单货品！",1000,"warning");
		return;
	}

	if (!$("form:first").valid()){
		return;
	}
	lBtn.start();
	$("form:first").submit();
}	

var stocksInfoJson=[];
function getStockInfo(findInfo){
	var url =$.getVirtualPath()+"/stock//stock/getStockInfo";
    $.ajax({
        type: 'get',
        dataType: "json",
        url: url,
        data: "searchKey="+findInfo,
        async: false,
        success: function (result) {
    		if(result!=null){
    			stocksInfoJson =result.data;
    		}else{
    			/* var stocksInfoJson =JSON.parse($("#stocksJson").val()); */
    		}
       	}
    });
} 

var showMark=true;

var stuffData=[];
function stocksShow(showNum){
	stuffData=[];

	var stocksJson =JSON.parse($("#stocksJson").val());
	var select=$('#cargoNo_'+showNum).select2({placeholder:"请选择货物信息",allowClear: true ,data : stuffData,query: function (query) {
        console.log(query);
        var data = {results: []};
        if(query.term!=null){
        	getStockInfo(query.term);
        }else{
        	getStockInfo("");
        }
		stocksInfoJson.forEach(function(element,index){
			element.stockCollocations.forEach(function(stockCollocation,index){
				data.results.push({
					id:stockCollocation.collocationId,
					text:element.cargo.cargoNo +"  "+ element.cargo.cargoName +"  " + stockCollocation.collocation.propertyNameOne + "/" + stockCollocation.collocation.propertyNameTwo +"  "+ stockCollocation.collocation.salePrice
				})
			});
		});
        
        query.callback(data);
    }});
	select.change(function(){
		var collocationId = $('#cargoNo_'+showNum).val();
		var repetitionNum = 0;
		$("select[name='cargoNo']").each(function(){
			if($(this).val()!=null&&$(this).val()!=""){
				if($(this).val()==collocationId){
					repetitionNum++;
				}
			}
			
		});
		stocksInfoJson.forEach(function(element,index){
			element.stockCollocations.forEach(function(stockCollocation,index){
				if(stockCollocation.collocationId==collocationId){
					
					$('#cargoId_'+showNum).val(element.cargoId);
					$('#collocationId_'+showNum).val(stockCollocation.collocationId);
					$('#cargoNoShow_'+showNum).val(element.cargo.cargoNo);
					$('#cargoName_'+showNum).val(element.cargo.cargoName);
					$('#unit_'+showNum).val(element.cargo.unit);
					$('#propertyName_'+showNum).val(stockCollocation.collocation.propertyNameOne + "/" + stockCollocation.collocation.propertyNameTwo);
					$('#collocationNum_'+showNum).val(1);
					$('#realPrice_'+showNum).val(stockCollocation.collocation.salePrice);
					$('#subtotal_'+showNum).val(stockCollocation.collocation.salePrice*1);
				}
			});
		});
		$("#cargoNoShow_"+showNum).parent().css("display","");
		$("#cargoName_"+showNum).parent().css("display","");
		$("#cargoNo_"+showNum).parent().css("display","none");
		updateBillingMoney();
		if(repetitionNum>1){
			$.showTips("此货品已存在！",1000,"warning");
		}
		addNewRow();
	});
	updateSubtotal(showNum);
	
}

function addNewRow(){
	var isAllow=0;
	var collocationIds=[];
	$("input[name='collocationId']").each(function(){
		collocationIds.push({
			id:$(this).val(),
			text:$(this).val()
		})
	});

	for(var i=0;i<collocationIds.length;i++){
		if(collocationIds[i].id==""){
			isAllow++;
			console.log(isAllow);
		}
	}
	if(isAllow<2){
		addData();
	}
	
}

function loadStock(){
	var stocksJson =JSON.parse($("#stocksJson").val());

	stocksJson.forEach(function(element,index){
		element.stockCollocations.forEach(function(stockCollocation,index){
			stuffData.push({
				id:stockCollocation.collocationId,
				text:element.cargo.cargoNo +"  "+ element.cargo.cargoName +"  " + stockCollocation.collocation.propertyNameOne + "/" + stockCollocation.collocation.propertyNameTwo +"  "+ stockCollocation.collocation.salePrice
			})
		});
	});
}

function updateSubtotal(showNum){
	$('#collocationNum_'+showNum).bind('input propertychange', function() {
		var count = parseInt($(this).val());
		$(this).val(count);
		if(isNaN(count)){
			count = 0;
			$(this).val(0);
		}else{
			var numValue = $(this).val();
			if(numValue.length>1){
				if(numValue.substring(1,2)!="."){
					if(numValue.substring(0,1)=='0'){
						$(this).val(parseFloat(numValue.substring(1,numValue.length)));
					}
				}

			}
		}
		var price = $('#realPrice_'+showNum).val();
		$('#subtotal_'+showNum).val(price*count);
		updateBillingMoney();
	});
	$('#realPrice_'+showNum).bind('input propertychange', function() {
		var price = parseFloat($(this).val());

		if(isNaN(price)){
			price = 0;
			$(this).val(0);
		}else{
			var numValue = $(this).val();
			if(numValue.length>1){
				if(numValue.substring(1,2)!="."){
					if(numValue.substring(0,1)=='0'){
						$(this).val(parseFloat(numValue.substring(1,numValue.length)));
					}
				}

			}
		}
		var count = $('#collocationNum_'+showNum).val();
		$('#subtotal_'+showNum).val(price*count);
		updateBillingMoney();
	});
	$('#collocationNum_'+showNum).focus();
}

function updateBillingMoney(){
	var billingMoney = 0;
	var discount = $("#discount").val();
	if(discount == "" || discount == null || discount == undefined || discount==0){
		$("input[name='subtotal']").each(function(){
			if($(this).val()!=null && $(this).val() != ""){
				billingMoney+= parseFloat($(this).val());
			}
							
		});

		$("#billingMoney").val(billingMoney);
    }else{
    	
    	$("input[name='subtotal']").each(function(){
    		if($(this).val()!=null && $(this).val() != ""){
				billingMoney+= parseFloat($(this).val());
			}			
		});
    	billingMoney=billingMoney*(discount/10);
		$("#billingMoney").val(billingMoney);
    }
}

function ValidateNumber(e, pnumber){
	if (!/^\d+[.]?\d*$/.test(pnumber))
	{
	e.value = /^\d+[.]?\d*/.exec(e.value);
	}else{
		
 	}
	return false;
}
</script>
<%@ include file="/WEB-INF/views/shared/base/scripts/jqueryui.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formtags.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formbuttons.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formpickers.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formselects.jsp"%>
<%@ include file="/WEB-INF/views/shared/base/scripts/limitless/default/formstyling.jsp"%>
<%@ include file="/WEB-INF/views/shared/master/dialog.jsp"%>
<%@ include file="/WEB-INF/views/shared/master/contentFooter.jsp"%>